﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Transactions;
using System.Web;
using System.Web.Http;
using FimetContoDeposito.BLL;
using FimetContoDeposito.BLL.Facades;
using FimetContoDeposito.BLL.Metadata;
using FimetContoDeposito.BLL.Objects;
using FimetContoDeposito.BLL.ResultSets;
using FimetContoDeposito.DAL;
using GrayParrot.Core;
using GrayParrot.Core.Json;
using GrayParrot.Web.Controls;
using GrayParrot.Web.Formly;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace FimetContoDeposito.Controllers
{
    public class AnagraficaDocumentiController : ApiController
    {
        #region Loading Fields...
        [HttpGet]
        public string[] LoadFields(Guid id)
        {
            string[] retValue = new string[2] { string.Empty, string.Empty };

            FCD_AnagraficaDocumenti obj = null;
            using (AnagraficaDocumentiFacade m_dc = AnagraficaDocumentiFacade.Create())
            {
                ReturnValue<FCD_AnagraficaDocumenti> m_objs = m_dc.Get(id);
                if (m_objs.HasValue)
                {
                    obj = m_objs.Value;
                }
            }

            if (obj != null)
            {
                var m_fields = FormlyHelper.ToFormly<AnagraficaDocumentiMetadata>(typeof(AnagraficaDocumentiMetadata));

                retValue[0] = JsonConvert.SerializeObject(m_fields);

                retValue[1] = JsonConvert.SerializeObject(obj);
            }

            //
            return retValue;
        }       
        #endregion

        public System.Net.Http.HttpResponseMessage Salva(JObject data)
        {
            System.Net.Http.HttpResponseMessage retValue = new HttpResponseMessage(HttpStatusCode.InternalServerError);

            dynamic json = data;
            Guid m_id = Guid.Parse(json.Id.ToString());

            FCD_AnagraficaDocumenti m_ad = json.ToObject<FCD_AnagraficaDocumenti>();

            using (AnagraficaDocumentiFacade m_dc = AnagraficaDocumentiFacade.Create())
            {
                ReturnValue<bool> m_res = m_dc.Salva(m_ad);

                string m_msg = string.Empty;
                if (m_res.HasValue && m_res.Value != null)
                {
                    retValue = Request.CreateResponse(HttpStatusCode.OK, m_res.Message);
                }
                else
                {
                    if (m_res.HasError)
                    {
                        retValue = Request.CreateResponse(HttpStatusCode.OK, m_res.Error.Message);
                    }
                    else
                    {
                        retValue = Request.CreateResponse(HttpStatusCode.OK, m_res.Message);
                    }
                }

                
            }

            return retValue;
        }
    }
}